<?php
/**
 * Created by PhpStorm.
 * User: gyq
 * Date: 2018/11/8
 * Time: 20:35
 */

namespace app\api\controller\v1;

use app\api\controller\BaseController;
use app\api\model\User;
use app\api\service\Token;
use app\api\validate\AddressNew;
use app\lib\exception\SuccessMessage;
use app\lib\exception\UserException;

class Address extends BaseController
{
    protected $beforeActionList = [
        'checkPrimaryScope' => ['only' => 'createOrUpdateAddress']
    ];

    public function createOrUpdateAddress()
    {
        $validate = new AddressNew();
        $validate->goCheck();
        $uid = Token::getTokenUid();
        /*检测该id是否存在，检测是否有address，有则更改，没有则新建*/
        $user = User::get($uid);
        if (!$user) {
            throw new UserException();
        }
        $dataArray = $validate->getDataByRule(input('post.'));
        $userAddress = $user->address;
        if (!$userAddress) {
            $user->address()->save($dataArray);
        } else {
            $user->address->save($dataArray);
        }
        return new SuccessMessage();
    }
}